﻿using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Data;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
namespace 门诊医生工作站
{
    public partial class frm_UserInfo : Form
    {
        public frm_UserInfo(string str)
        {
            InitializeComponent();
            this.txb_No.Text = str;
        }
        //点击载入按钮
        private void btn_In_Click(object sender, EventArgs e)
        {
            SqlConnection sqlConnection = new SqlConnection();
            sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.Connection = sqlConnection;
            SqlCommand sqlCommand2 = new SqlCommand();
            sqlCommand2.Connection = sqlConnection;
            DataTable dataTable = new DataTable();//保存一整张表
            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();//sql适配器
            sqlDataAdapter.SelectCommand = sqlCommand2;//接收查询结果
            sqlCommand2.CommandText = $"SELECT * FROM dbo.tb_Office";
            sqlCommand.CommandText = $"SELECT* FROM dbo.tb_Doctor WHERE No=@No";
            sqlCommand.Parameters.AddWithValue("No", this.txb_No.Text);//防止外部攻击
            sqlConnection.Open();
            sqlDataAdapter.Fill(dataTable);//将接收到的结果填充到dataTable里面
            this.cmb_Office.DataSource = dataTable;
            this.cmb_Office.ValueMember = "No";//选中的No对应OfficeNo
            this.cmb_Office.DisplayMember = "Name";//要显示的列名称
            SqlDataReader sqlDataReader= sqlCommand.ExecuteReader();//sqlDataReader以行为单位读取数据
            byte[] photoBytes=null;//先定义photoBytes为空
            if (sqlDataReader.Read())//一次读取一行数据
            {
            this.txb_No.Text = sqlDataReader["No"].ToString();
            this.txb_Name.Text = sqlDataReader["Name"].ToString();
            this.txb_ID.Text = sqlDataReader["ID"].ToString();
            this.cmb_Office.SelectedValue = (int)sqlDataReader["OfficeNo"];
            this.txb_Phone.Text = sqlDataReader["Phone"].ToString();
            this.rdb_Male.Checked = (bool)sqlDataReader["Gender"];//根据bit的0（女）或1（男）转变为bool的false或true
            this.rdb_Female.Checked = !this.rdb_Male.Checked;
            this.dtp_BirthDate.Value =(DateTime)sqlDataReader["BirthDate"];
            this.txb_Age.Text = sqlDataReader["Age"].ToString();
            photoBytes = sqlDataReader["Photo"]==DBNull.Value?null:(byte[])sqlDataReader["Photo"];
            //字节数组不能在空值情况下强制类型转换,判断该属性是不是为数据库空值，若是则返回null,不是则进行类型转换；
            }
            else 
            {
                MessageBox.Show("查无此人！");
                this.txb_No.Focus();
                this.txb_No.SelectAll();
            }           
            if (photoBytes != null)//若不为空，则说明有选定图片
            {
                MemoryStream memoryStream = new MemoryStream(photoBytes);
                this.ptb_Image.Image = Image.FromStream(memoryStream);
            }

            
            sqlDataReader.Close();//sqlDataReader自己的关闭

        }
        //点击更新按钮
        private void btn_Renew_Click(object sender, EventArgs e)
        {
            MemoryStream memoryStream = new MemoryStream();//定义一个内存流
            this.ptb_Image.Image.Save(memoryStream,ImageFormat.Bmp);//采用图片控件自带的图片保存方法，将图片格式为bmp的图片字节写入内存流
            byte[] photoBytes=new byte[memoryStream.Length];//定义一个字节数组与数据库中photo属性的varbinary对应，用于保存照片的字节,长度与内存流的长度一致；
            memoryStream.Seek(0,SeekOrigin.Begin);//将内存流里的数据复位到第一个字节
            memoryStream.Read(photoBytes, 0, photoBytes.Length);//将内存流的内容写入到photoBytes里面，第二个参数为偏移量
            if (this.txb_Name.Text==""||this.txb_ID.Text==""||this.txb_Phone.Text==""/*||this.rdb_Male.Checked==null*/||this.txb_Age.Text==""||this.cmb_Office.SelectedValue== null)
            {
                MessageBox.Show("请先载入信息！");
            }
            else
            {
            SqlConnection sqlConnection = new SqlConnection();
            sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
            SqlCommand sqlCommand1 = new SqlCommand();
            sqlCommand1.Connection = sqlConnection;
            sqlCommand1.CommandText = $"UPDATE dbo.tb_Doctor "
                                   + $" SET"
                                   + $" Name=@Name"
                                   + $" ,Gender=@Gende"
                                   + $" ,BirthDate=@BirthDate"
                                   + $" ,ID=@ID"
                                   + $" ,OfficeNo=@OfficeNo"
                                   + $" ,Phone=@Phone"
                                   + $" ,Age=@Age"
                                   + $" ,Photo=@Photo"
                                   + $" WHERE No=@No";
                sqlCommand1.Parameters.AddWithValue("@Name", this.txb_Name.Text);
                sqlCommand1.Parameters.AddWithValue("@Gende", this.rdb_Male.Checked);
                sqlCommand1.Parameters.AddWithValue("@BirthDate", this.dtp_BirthDate.Value);
                sqlCommand1.Parameters.AddWithValue("@ID", this.txb_ID.Text);
                sqlCommand1.Parameters.AddWithValue("@OfficeNo", this.cmb_Office.SelectedValue);
                sqlCommand1.Parameters.AddWithValue("@Phone", this.txb_Phone.Text);
                sqlCommand1.Parameters.AddWithValue("@Age", this.txb_Age.Text);
                sqlCommand1.Parameters.AddWithValue("@No", this.txb_No.Text);
                sqlCommand1.Parameters.AddWithValue("@Photo", photoBytes);
                SqlCommand sqlCommand2 = new SqlCommand();
            sqlCommand2.Connection = sqlConnection;
            sqlCommand2.CommandText =  $"UPDATE dbo.tb_User "
                                     + $" SET"
                                     + $" Name=@Name"
                                     + $" ,OfficeNo=@OfficeNo"
                                     + $" WHERE No=@No";
            sqlCommand2.Parameters.AddWithValue("@Name", this.txb_Name.Text);
            sqlCommand2.Parameters.AddWithValue("@OfficeNo", this.cmb_Office.SelectedValue);
            sqlCommand2.Parameters.AddWithValue("@No", this.txb_No.Text);
            sqlConnection.Open();                       
            int rowAffected1 = sqlCommand1.ExecuteNonQuery();
            int rowAffected2 = sqlCommand2.ExecuteNonQuery();
                if (rowAffected1!=0)
                {
                    DialogResult messageboxResult = MessageBox.Show("确定更新信息吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (messageboxResult == DialogResult.Yes)
                   {
                      MessageBox.Show($"更新{rowAffected1}行。");                                   
                   }
                }
                //if (rowAffected2 != 0)
                //{
                //    MessageBox.Show("用户表更新成功");
                //}
                sqlConnection.Close();//sql连接关闭
            }
        }
        //点击修改密码按钮
        private void btn_Modi_Click(object sender, EventArgs e)
        {            
            this.Hide();
            new frm_ModiPassword().Show();
        }
        //点击头像设置按钮
        private void btn_Image_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog()
            {
                Title = "打开照片文件",//打开文件夹的标题
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),//指定文件夹打开路径
                Filter = "图像文件|*.jpg;*.bmp"//筛选图像文件格式
            };           
            openFileDialog.ShowDialog();
            if (openFileDialog.ShowDialog()==DialogResult.OK)//当点击“打开”按钮才进行以下操作，若点击“取消”则什么都不干
            {
                string fileName = openFileDialog.FileName;//保存选定图像文件的文件名
                this.ptb_Image.Image = Image.FromFile(fileName);//返回选定文件名的图像文件的图像,需要using System.Drawing;
            }
            
        }
    }
}
